<template>
    <div class="flex h-screen w-screen items-center justify-center  bg-gray-100">
        <div class="w-80 md:w-96 bg-white p-5 rounded-lg shadow-md min-w-96" v-if="flag">
            <span class="flex items-center justify-center w-full">
                <img src="@/assets/primeVue.svg" class=" mr-4" alt="">
                <h2 class="text-center">智慧阅卷平台</h2>
            </span>
            <div v-focustrap class="w-full mt-5">
                <InputGroup class="mb-4 h-10">
                    <InputGroupAddon>
                        <i class="pi pi-user"></i>
                    </InputGroupAddon>
                    <InputText placeholder="用户名" v-model="account" />
                    <InlineMessage v-if="accountError" class="ml-2 rounded-lg">{{ accountError }}</InlineMessage>
                </InputGroup>
                <!-- <small class="p-error">{{ usernameError || '&nbsp;' }}</small> -->
                <InputGroup class="mb-4 h-10">
                    <InputGroupAddon>
                        <i class="pi pi-lock"></i>
                    </InputGroupAddon>
                    <Password placeholder="密码" v-model="password" promptLabel="输入密码" weakLabel="简单" mediumLabel="正常"
                        strongLabel="强" toggleMask />
                    <InlineMessage v-if="passwordError" class="ml-2 rounded-lg">{{ passwordError }}</InlineMessage>
                </InputGroup>

                <InputGroup class="mb-4 h-10 ">
                    <InputGroupAddon>
                        昵称
                    </InputGroupAddon>
                    <InputText placeholder="昵称" v-model="nickname" />
                    <InlineMessage v-if="nicknameError" class="ml-2 rounded-lg">{{ nicknameError }}</InlineMessage>
                </InputGroup>
                <InputGroup class="mb-4 h-10 ">
                    <InputGroupAddon>
                        姓名
                    </InputGroupAddon>
                    <InputText placeholder="真实姓名" v-model="realname" />
                    <InlineMessage v-if="realnameError" class="ml-2 rounded-lg">{{ realnameError }}</InlineMessage>
                </InputGroup>
                <InputGroup class="mb-4 h-10">
                    <InputGroupAddon>
                        性别
                    </InputGroupAddon>
                    <InputGroupAddon>
                        <RadioButton v-model="gender" inputId="male" name="gender" value="男" />
                    </InputGroupAddon>
                    <InputText placeholder="男" disabled />
                    <InputGroupAddon>
                        <RadioButton v-model="gender" inputId="female" name="gender" value="女" />
                    </InputGroupAddon>
                    <InputText placeholder="女" disabled />
                </InputGroup>
                <InputGroup class="mb-4 h-10">
                    <InputGroupAddon>
                        <i class="pi pi-prime"></i>
                    </InputGroupAddon>
                    <Dropdown class="items-center pl-2" v-model="selectedRole" :options="roles" optionLabel="name"
                        placeholder="选择身份" />
                </InputGroup>
                <InputGroup class="mb-4 h-10">
                    <InputGroupAddon>
                        <i class="pi pi-envelope"></i>
                    </InputGroupAddon>
                    <InputText placeholder="邮箱" v-model="email" />
                    <InputGroupAddon>.com</InputGroupAddon>
                </InputGroup>
                <InlineMessage v-if="emailError" class="m-2 rounded-lg p-2">{{ emailError }}</InlineMessage>
                <InputGroup class="mb-4 h-10">
                    <InputGroupAddon>
                        <i class="pi pi-phone"></i>
                    </InputGroupAddon>
                    <InputText placeholder="手机号" v-model="phone" />
                    <InlineMessage v-if="phoneError" class="ml-2 rounded-lg">{{ phoneError }}</InlineMessage>
                </InputGroup>
                <Button type="submit" label="立即注册" class="w-full mb-2" @click="onSubmit" />
                <span class=" text-gray-400">已有账号？</span><a href="/auth/login" class=" text-blue-600">去登录</a>
            </div>
        </div>
        <div class="w-80 md:w-96 bg-white p-5 rounded-lg shadow-md flex flex-col items-center" v-else>
            <div class=" bg-[#10B981] rounded-full -mt-12 mb-5">
                <i class="pi pi-check text-white m-5 text-4xl font-bold"></i>
            </div>
            <h3 class="mb-5">恭喜您，成功注册智慧阅卷平台账号！</h3>
            <div class="text-gray-400">
                <p class="mb-3">您的账号信息为：</p>
                <p class="mb-3">账号：<span class="text-blue-500">{{ userStore.userInfo.account }}</span></p>
                <p class="mb-3">昵称：<span class="text-blue-500">{{ userStore.userInfo.nickname }}</span></p>
                <p class="mb-5">密码：<span class="text-blue-500">{{password1 }}</span></p>
            </div>

            <div class="flex align-items-center gap-2 mt-4">
                <Button label="进入系统" @click="acceptCallback" class="md:w-60"></Button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router';

import InlineMessage from 'primevue/inlinemessage';
import Password from 'primevue/password';
import Dropdown from 'primevue/dropdown';
import RadioButton from 'primevue/radiobutton';
import InputGroup from 'primevue/inputgroup';
import InputGroupAddon from 'primevue/inputgroupaddon';
import { useToast } from 'primevue/usetoast';
import { useField, useForm } from 'vee-validate'
import { RegisterApi } from "@/api/register";
import { useUserStore } from "@/stores/modules/user";
const userStore = useUserStore();

// @ts-ignore
import * as yup from 'yup';

// 在你的组件中
const router = useRouter();

// 注册接口类型
interface RegisterForm {
    account: string,
    nickname: string,
    realname: string,
    gender: number,
    avatar: string,
    role: number,
    phone: string,
    email: string,
    password: string,
}


// const redirectToLogin = () => {
//     router.push('/auth/login');
// }

// 注册成功后，显示注册信息页面      
const flag = ref(true);

const gender = ref('男');


const roles = ref([
    { name: '学生', code: 1 },
    { name: '老师', code: 2 },
    { name: '管理员', code: 3 }
]);

const password1 = ref('');

const { handleSubmit, resetForm } = useForm();
const toast = useToast();
const schema = yup.object({
    account: yup.string().required('用户名不能为空'),
    password: yup.string().required('密码不能为空').min(6, '密码长度至少为6个字符'),
    nickname: yup.string().required('昵称不能为空'),
    realname: yup.string().required('真实姓名不能为空').matches(/^[\u4e00-\u9fa5]+$/, '真实姓名必须是中文字符'),
    // gender: yup.string().required('性别不能为空'),
    email: yup.string().required('邮箱不能为空').email('请输入有效的电子邮件地址'),
    phone: yup.string().required('手机号不能为空').matches(/^[1][3,4,5,7,8][0-9]{9}$/, '手机号格式不正确'),
    // role: yup.number().required('请选择身份'),
    avatar: yup.string().notRequired(),// 非必填字段
});
const { value: account, errorMessage: accountError } = useField('account', schema.fields.account);
const { value: password, errorMessage: passwordError } = useField('password', schema.fields.password);
const { value: nickname, errorMessage: nicknameError } = useField('nickname', schema.fields.nickname);
const { value: realname, errorMessage: realnameError } = useField('realname', schema.fields.realname);
const { value: email, errorMessage: emailError } = useField('email', schema.fields.email);
const { value: phone, errorMessage: phoneError } = useField('phone', schema.fields.phone);

const selectedRole = ref({ name: '老师', code: 2 });


const onSubmit = handleSubmit((values: RegisterForm) => {
    // 处理表单提交...
    resetForm()
    values.role = roles.value[0].code;     // 例如，设置默认角色为 '学生'
    values.gender = gender.value == '男' ? 1 : 2; // 转换性别为数字
    values.avatar = 'http://paperjudge.oss-cn-guangzhou.aliyuncs.com/2024/03/19/2ed8fe39-6cfd-4851-8e54-318c8f237ebc.png';    // 无头像
    password1.value = password.value; // 保存密码到全局变量，用于登录页面的密码校验

    // alert(JSON.stringify(values, null, 2));

    RegisterApi(values).then(res => {
        toast.add({ severity: 'info', summary: '注册成功', detail: '请确认你的信息' });
        // console.log(res);
        // 注册成功后，保存 token 到 localStorage
        // window.localStorage.setItem("token", res.data.token);
        userStore.setToken(res.data.token);
        userStore.setUserInfo(res.data);

        flag.value = false;
    }).catch(error => {
        toast.add({ severity: 'error', summary: '注册失败', detail: error.message, life: 3000 });
    });
});

const acceptCallback = () => {
    // 确认信息后，跳转主页
    router.push({ name: 'home' }); // 假设你的主页路由配置了 'name' 
}

</script>